package handlers

import (
	"encoding/json"
	"net/http"
	"os"
	"time"

	"homepage-backend/internal/config"
	"homepage-backend/internal/models"
	"homepage-backend/internal/services"

	"github.com/golang-jwt/jwt/v5"
)

// AnnouncementHandler 处理公告请求和管理
func AnnouncementHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		announcements, err := services.LoadAnnouncements(config.GlobalConfig.AnnouncementsFilePath)
		if err != nil {
			http.Error(w, "Failed to load announcements", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(announcements)
		return
	}
	if r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE" {
		AdminAuthMiddleware(announcementHandlerWrite)(w, r)
		return
	}
}

// announcementHandlerWrite 仅用于POST/PUT/DELETE，已通过JWT校验
func announcementHandlerWrite(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		var ann models.Announcement
		if err := json.NewDecoder(r.Body).Decode(&ann); err != nil {
			http.Error(w, "请求数据无效", http.StatusBadRequest)
			return
		}
		ann.PublishTime = time.Now()
		err := services.AddAnnouncement(config.GlobalConfig.AnnouncementsFilePath, ann)
		if err != nil {
			http.Error(w, "添加失败", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusCreated)
		w.Write([]byte("ok"))
	case "PUT":
		var ann models.Announcement
		if err := json.NewDecoder(r.Body).Decode(&ann); err != nil {
			http.Error(w, "请求数据无效", http.StatusBadRequest)
			return
		}
		err := services.UpdateAnnouncement(config.GlobalConfig.AnnouncementsFilePath, ann)
		if err != nil {
			http.Error(w, "修改失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
	case "DELETE":
		id := r.URL.Query().Get("id")
		if id == "" {
			http.Error(w, "缺少id参数", http.StatusBadRequest)
			return
		}
		err := services.DeleteAnnouncement(config.GlobalConfig.AnnouncementsFilePath, id)
		if err != nil {
			http.Error(w, "删除失败", http.StatusInternalServerError)
			return
		}
		w.Write([]byte("ok"))
	default:
		http.Error(w, "方法不允许", http.StatusMethodNotAllowed)
	}
}

// CheckJWT 校验JWT token
func CheckJWT(tokenStr string) bool {
	jwtSecret := os.Getenv("ADMIN_JWT_SECRET")
	if jwtSecret == "" {
		jwtSecret = "changeme-please"
	}
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		return []byte(jwtSecret), nil
	})
	return err == nil && token.Valid
}
